<template>
  <div>
    <FormPanel ref="form" :list="formList" formType="add" :isSubmitBtn="false" labelWidth="120" @formChange="changeHandle" />
    <div class="btnWrap">
      <!-- <p class="test">说明:成本价不含税</p> -->
      <el-button @click="closeDrawer(1)">取 消</el-button>
      <el-button type="primary" @click="closeDrawer(2)">保 存</el-button>
    </div>

    <!-- 配件选择弹窗 -->
    <BaseDialog :visible.sync="partSelectVisible" title="配件选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <chosePart mode="single" @close="partSelectVisible = false" @onConfirm="handleDetailSelectConfirm" />
    </BaseDialog>
    <!-- 库位 -->
    <BaseDialog :visible.sync="positionSelectVisible" title="库位选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <position :params="positionParams" @close="positionSelectVisible = false" @onConfirm="handlePositionSelectConfirm" />
    </BaseDialog>
  </div>
</template>
<script>
import {
  newBuild,
  getpartStocksList,
  getDealertCode,
  getfindStorageCode,
  getquerypartGroupCodes,
  getpartInfos,
  querypartInfo,
  getStockQuantity,
  getPosition,
  savePartInfo,
  save,
  queryUsableLocations
} from '@/api/part/inventoryManager/inventoryManager/index';
import { dictionary } from '@/utils/dictMixin';
import pinyin, { STYLE_FIRST_LETTER } from '@/components/Pinyin/index';
import { getBrandList } from '@/api/common/cars/masterDataCars';
import { addPartInfo, ModifyPartInfo, queryUnitCode } from '@/api/part/partInfo';
import { findAllRepair } from '@/api/repair/basicParameters';
import { log } from 'util';
import { notifyAction } from '@/utils';
import { queryControlLocations } from '@/api/part/common';
import chosePart from './chosePart';
import { getPinpSelect } from '@/api/repair/repairReception/customer/brand.js';
import partSelect from '@/pages/part/partPurchase/purchaseOrder/partSelect';
import position from '@/pages/part/common/position';

export default {
  components: {
    chosePart,
    position
  },
  // props: {
  //   Fdata: {
  //     type: Object,
  //     default: () => ({})
  //   }
  // },
  mixins: [dictionary],
  data() {
    this.commitData = null;
    // this.basetable = null;
    return {
      formList: this.createFrom(),
      partInfoList: [],
      columns: this.createTable(),
      locationLists: [],
      formDataList: {},
      flag: null,
      Fdata: {},
      storageList: [],
      defaultStorage: '',
      partSelectVisible: false, // 是否显示配件选择弹窗
      positionSelectVisible: false, // 是否显示库位选择弹窗
      positionParams: {}
    };
  },
  computed: {
    salerPrice() {
      return this.formList.find(item => item.fieldName == 'salesPrice').initialValue;
    }
  },
  // watch: {
  //   Fdata: {
  //     handler(newVal, oldVal) {
  //       console.log('Fdata', newVal);
  //       this.formList.forEach(x => {
  //         x.initialValue = newVal[x.fieldName];
  //       });
  //     },
  //     deep: true
  //   }
  // },
  created() {
    this.getDictlist();
  },
  mounted() {
    // this.basetable = this.$refs.basetable.$refs.pageTable;
    // console.log('mounted::', this.Fdata);
    // this.formList.forEach(x => {
    //   x.initialValue = this.Fdata[x.fieldName];
    // });
    this.getStorage();
  },
  methods: {
    // 选择库位(弹窗)
    handlePositionSelectConfirm(val) {
      this.formList.find(item => item.fieldName == 'storagePositionCode').initialValue = val[0].storagePositionCode;
      this.positionSelectVisible = false;
    },
    // 点击库位搜索
    handleSearchPosition() {
      let storageCode = this.formList.find(item => item.fieldName == 'storageCode').initialValue;
      if (!storageCode) {
        return this.$notify.warning({ title: '提示信息', message: '请选择仓库' });
      }
      this.positionParams.storageCode = storageCode;
      this.positionParams.partNo = this.formList.find(item => item.fieldName == 'partNo').initialValue;
      this.positionSelectVisible = true;
    },

    // 选择库位
    changeStoragePosition(val) {
      // console.log(val);

      if (val) {
        return this.$notify.warning({ title: '提示信息', message: '请输入配件代码' });
      }
    },
    // 选择仓库之后得回调
    async storageChange(val) {
      let res = await getPosition({ storageCode: val });
      this.positionParams.storageCode = storageCode;
      if (res.resultCode == 200) {
        try {
          if (res.data.length > 0) {
            if (res.data[0].error) {
              this.$notify.warning({ title: '错误提示', message: '该仓库没有库位可以使用' });
              this.formList.find(item => item.fieldName === 'storagePositionCode').initialValue = '';
            } else {
              this.formList.find(item => item.fieldName === 'storagePositionCode').itemList = res.data.map(x => ({ text: x.storagePositionCode, value: x.storagePositionCode }));
              this.formList.find(item => item.fieldName === 'storagePositionCode').initialValue = '';
            }
          } else {
            this.$notify.warning({ title: '错误提示', message: '该仓库没有库位可以使用' });

            // this.formList.find(item => item.fieldName === 'storageCode').itemList = this.storageList;
            this.formList.find(item => item.fieldName === 'storageCode').initialValue = '';
            this.formList.find(item => item.fieldName === 'storagePositionCode').itemList = [];
          }
        } catch (error) {}
      }
      // if (this.formDataList.partNo == null || this.formDataList.partNo == '') {
      //   this.queryEmptyLocation(false, true);
      // } else {
      //   this.formDataList.storageCode = val;
      //   this.queryEmptyLocation(true, true);
      // }
    },
    // 仓库条件变为初始条件

    // 选择仓库配件之后的回调,更新库存信息
    async queryEmptyLocation(flag, val) {
      if (!val) {
        this.formDataList.storageCode = flag;
      }
      this.formDataList.partNo = this.formList.find(item => item.fieldName == 'partNo').initialValue;
      if (this.formDataList.storageCode == null || this.formDataList.storageCode == '') {
        this.$notify.warning({ title: '消息提示', message: '请先填写仓库信息' });
        return;
      }
      let res = null;
      if (flag) {
        res = await queryUsableLocations({ storageCode: this.formDataList.storageCode, partNo: this.formDataList.partNo });
      } else {
        res = await getPosition({ storageCode: this.formDataList.storageCode });
      }

      if (res.resultCode == 200) {
        try {
          if (res.data[0].error) {
            this.$notify.warning({ title: '错误提示', message: '该仓库没有库位可以使用' });
          } else {
            this.formList.find(item => item.fieldName === 'storagePositionCode').itemList = res.data.map(x => ({ text: x.storagePositionCode, value: x.storagePositionCode }));
          }
        } catch (error) {}
      }
      this.formList.find(x => x.fieldName == 'storagePositionCode').initialValue = '';
    },
    createFrom() {
      return [
        // {
        //   type: 'SELECT',
        //   label: '品牌',
        //   fieldName: 'brand',
        //   placeholder: '请选择...',
        //   initialValue: '',
        //   disabled: true,
        //   itemList: [
        //     { text: 'BEIJING', value: 'beqi' },
        //     { text: 'ARCFOX', value: 'arc' }
        //   ]
        // },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  this.partSelectVisible = true;
                }}
              ></el-button>
            );
          }
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName',
          disabled: true,
          initialValue: '',
          rules: [{ required: true, message: '请输入配件名称', trigger: 'blur' }],
          change: props => {
            this.changePartName(props);
          }
        },
        {
          type: 'SELECT',
          label: '数据来源',
          fieldName: 'downTag',
          initialValue: '10041002',
          disabled: true,
          itemList: [
            { text: '厂端下发', value: '10041001' },
            { text: '店端自建', value: '10041002' }
          ]
        },
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'storageCode',
          placeholder: '请选择',
          initialValue: '',
          disabled: false,
          itemList: [],
          rules: [{ required: true, message: '请输入仓库', trigger: 'blur' }],
          change: this.queryEmptyLocation
        },
        {
          type: 'INPUT',
          label: '库位代码',
          fieldName: 'storagePositionCode',
          initialValue: '',
          rules: [{ required: true, message: '请输入库位', trigger: 'blur' }],
          disabled: false,
          // itemList: [],
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.handleSearchPosition}></el-button>;
          }
          // disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '成本单价',
          fieldName: 'costPrice',
          initialValue: '',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'partStatus',
          initialValue: '10041002',
          placeholder: '请选择',
          disabled: false,
          itemList: [
            { text: '停用', value: '10041001' },
            { text: '启用', value: '10041002' }
          ]
          // change: this.queryEmptyLocation
        },
        // {
        //   type: 'INPUT',
        //   label: '加价率',
        //   fieldName: 'ADD_RATE',
        //   initialValue: '',
        // },

        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '库存数量',
          fieldName: 'stockQuantity',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '可用库存',
          fieldName: 'usableQuantity',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '锁定量',
          fieldName: 'lockedQuantity',
          initialValue: '',
          disabled: true
        },
        // {
        //   type: 'INPUT_NUMBER',
        //   label: '建议销售价',
        //   fieldName: 'notTaxInstructPrice',
        //   initialValue: '',
        //   disabled: true
        // },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '最大库存',
          fieldName: 'maxStock',
          initialValue: ''
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '最小库存',
          fieldName: 'minStock',
          initialValue: ''
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '安全库存',
          fieldName: 'safeStock',
          initialValue: ''
        }
        // {
        //   type: 'INPUT',
        //   label: '呆滞天数',
        //   fieldName: 'sluggishDays',
        //   disabled: true,
        //   initialValue: ''
        // }

        // {
        //   type: 'INPUT_NUMBER',
        //   precision: 2,
        //   label: '终端建议零售价格',
        //   fieldName: 'insurancePrice',
        //   initialValue: ''
        // },
        // {
        //   type: 'INPUT',
        //   label: '替代配件',
        //   fieldName: 'optionNo',
        //   initialValue: '',
        //   disabled: true
        // },
      ];
    },
    createTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '年度',
          dataIndex: 'YEAR',
          sorter: true,
          filter: true
        },
        {
          title: '月度',
          dataIndex: 'month',
          sorter: true,
          filter: true
        },
        {
          title: '出库数量',
          dataIndex: 'outQuantity',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'input'
        },
        {
          title: '入库数量',
          dataIndex: 'inQuantity',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'input'
        }
      ];
    },
    async getStorage() {
      const res = await getfindStorageCode();
      this.formList.find(item => item.fieldName === 'storageCode').itemList = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      this.storageList = res.data.map(x => ({ storageType: x.STORAGE_TYPE, storageCode: x.STORAGE_CODE, oemTag: x.OEM_TAG }));
      // this.form[0].itemList = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
    },
    changeHandle(val) {
      this.commitData = val;
    },
    async closeDrawer(type) {
      if (type == 1) {
        this.$emit('close', false);
      } else {
        let formData = await this.$refs.form.GET_FORM_DATA();
        if (formData[0]) {
          let keys = Object.keys(formData[0]);
          notifyAction(formData[0][keys[0]][0].message, 'warning');
          return;
        }
        this.commitData = formData[1];
        if (this.commitData['storageCode'] == 'OEMK') {
          this.$notify({ title: '提示信息', message: '店端限制OEM仓库保存', type: 'warning' });
          return;
        }
        this.commitData['flg'] = 'A';
        this.commitData['costSalesPrice'] = this.commitData['salesPrice'];
        this.commitData['costWholesalesPrice'] = this.commitData['wholesalesPrice'];
        let storageType = this.storageList.find(x => x.storageCode == this.commitData.storageCode).storageType;
        let oemTag = this.storageList.find(x => x.storageCode == this.commitData.storageCode).oemTag;
        let flag = true;
        if (oemTag == '10451002' && this.Fdata.downTag == '10041002') {
          this.$notify.warning({ title: '提示信息', message: '原厂库不允许创建非原厂件库存' });
          flag = false;
          return;
        }
        if (storageType != this.Fdata.partType) {
          this.$notify.warning({ title: '提示信息', message: '只能创建相同油电属性的仓库库存' });
          flag = false;
        }
        if (flag) {
          let obj = { dmstable: [this.commitData], dmsTable: [this.commitData] };
          let res = await save(obj);
          if (res.resultCode == '200') {
            this.$notify.success({ title: '提示信息', message: '保存成功' });
            this.$emit('addChange');
          }
        }
      }
    },
    // 查询品牌
    async getBrand() {
      // const res = await getBrandList();
      const res = await getPinpSelect();
      if (res.resultCode == 200) {
        if (res.data && res.data.length > 0) {
          this.formList.find(item => item.fieldName == 'brand').itemList = res.data.map(x => ({ text: x.brandName, value: x.brandCode + '' }));
        }
      }
    },
    // 获取数据字典
    async getDictlist() {
      // 获取
      // try {
      //   let res = (await getfindStorageCode()).data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      //   this.storageList = res;
      //   this.formList.find(item => item.fieldName === 'storageCode').itemList = res;
      // } catch (err) {
      //   console.log(err, '获取仓库失败');
      // }

      try {
        const res3 = await queryUnitCode();
        // this.formList.find(item => item.fieldName == 'unitCode').itemList = res3.data.map(x => ({ text: x.UNIT_NAME, value: x.UNIT_CODE }));
      } catch (err) {
        console.log('获取单位失败', err);
      }

      try {
        let res1 = (await getquerypartGroupCodes()).data.map(x => ({ text: x.PART_MODEL_GROUP_NAME, value: x.PART_MODEL_GROUP_CODE }));
      } catch (err) {
        console.log(err);
      }

      try {
        let res4 = await findAllRepair();
        this.formList.find(item => item.fieldName == 'taxRate').initialValue = res4.data['1003'];
        this.defaultStorage = res4.data['1100'];
        this.formList.find(item => item.fieldName == 'storageCode').initialValue = res4.data['1100'];
      } catch (err) {
        console.log(err);
      }

      this.queryEmptyLocation(false, false);
      // this.getBrand();
    },
    // 点击配件搜索按钮
    handleSearchPart() {
      let storageCode = this.formList.find(item => item.fieldName === 'storageCode').initialValue;
      if (!storageCode) {
        this.$notify.warning({ title: '提示', message: '请先选择仓库' });
        return;
      }
      this.partSelectVisible = true;
    },
    // 配件选择点击确定
    async handleDetailSelectConfirm(e) {
      this.Fdata = e;
      let partData = e;
      console.log(e, 1231);

      this.formList.map(item => {
        if (partData[item.fieldName] && item.fieldName != 'storageCode' && item.fieldName != 'stockQuantity' && item.fieldName != 'partStatus') {
          item.initialValue = partData[item.fieldName];
        }
        if (item.fieldName == 'salesPrice') {
          item.initialValue = partData['costSalesPrice'];
        }
        if (item.fieldName == 'minPackage') {
          item.initialValue = partData['packageLiaght'];
        }
      });
      // this.formList.find(item => item.fieldName == 'partNo').initialValue = partData.partNo;
      // this.formList.find(item => item.fieldName == 'partName').initialValue = partData.partName;
      // 拼音码
      // this.formList.find(item => item.fieldName == 'spellCode').initialValue = pinyin(partData.partName, { style: STYLE_FIRST_LETTER })
      //   .flat()
      //   .join('');
      this.partSelectVisible = false;
      // 历史入库信息
      let storageCode = this.formList.find(item => item.fieldName === 'storageCode').initialValue;
      // let storageCode = partData.storageCode;
      let res = await getStockQuantity(partData.partNo, storageCode);
      // this.basetable.EXECUTE_INSERT(res.data);
      // 查询库位
      this.positionParams.storageCode = storageCode;
      this.positionParams.partNo = partData.partNo;
      // let positionRes = await queryControlLocations(this.positionParams);
      // if (positionRes.resultCode == 200) {
      //   if (positionRes.data.rows.length && positionRes.data.rows[0].storagePositionCode) {
      //     this.formList.find(item => item.fieldName === 'storagePositionCode').initialValue = positionRes.data.rows[0].storagePositionCode;
      //   }
      // }
      // console.log(positionRes, '库位');
    },
    // 配件代码改变判断条件(旧逻辑，废弃)
    async changePartNo(val) {
      if (!val) {
        this.$notify.warning({ title: '提示信息', message: '请先填写配件代码' });
        retrun;
      }
      let storageCode = this.formList.find(item => item.fieldName === 'storageCode').initialValue;
      if (storageCode == '' || storageCode == null) {
        // if (this.formList[0].initialValue == '' || this.formList[0].initialValue == null) {
        this.$notify.warning({ title: '提示信息', message: '请先填写' + this.formList[0].label });
      }
      let res = await querypartInfo(val);
      if (res.resultCode == '200') {
        this.queryEmptyLocation(true);
      }
      if (res.data.length != 0) {
        let res4 = res.data[0];
        // 判断配件是否是厂端下发
        if (res4['oemTag'] == '10451002') {
          this.formList.find(item => item.fieldName == 'limitPrice').disabled = true;
        } else {
          this.formList.find(item => item.fieldName == 'limitPrice').disabled = false;
        }
        res4.storageCode = storageCode;
        this.formList.forEach(x => {
          if (x.fieldName == 'salesPrice') {
            x.initialValue = res4['costSalesPrice'];
          } else if (x.fieldName == 'wholesalesPrice') {
            x.initialValue = res4['costWholesalesPrice'];
          } else {
            x.initialValue = res4[x.fieldName];
          }
        });
        let res2 = await getStockQuantity(val, storageCode);
        // this.basetable.EXECUTE_INSERT(res2.data);
      } else {
        console.log('该配件不存在需要添加新的配件信息');
        this.flag = 'A';
        // 店端自建配件限制OEM仓库保存
        // this.formList.find(item => item.fieldName == 'storageCode').initialValue = 'OEMK';
        this.queryEmptyLocation(false);
        this.formList.find(item => item.fieldName == 'limitPrice').disabled = false;
        this.formList.find(item => item.fieldName == 'storagePositionCode').initialValue = '';
        // if (this.formList.find(item => item.fieldName == 'storageCode')) {
        //   this.formList.find(item => item.fieldName == 'storageCode').disabled = true;
        // }
        return this.$notify.warning({ title: '提示信息', message: '该配件不存在，需要添加新的配件信息' });
      }
    }
  }
};
</script>
<style lang="less" scoped>
.test {
  text-align: left;
  color: red;
  display: block;
  float: left;
}
.btnWrap {
  position: absolute;
  left: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 9;
  border-top: 1px solid rgb(233, 233, 233);
  padding: 10px 20px;
  background: rgb(255, 255, 255);
  text-align: right;
}
</style>
